//
//  AppDelegate.m
//  suRead
//
//  Created by bao on 15/9/7.
//  Copyright (c) 2015年 bao. All rights reserved.
//

#import "AppDelegate.h"
#import "AppWizardView.h"
#import "AppADView.h"
#import "ServiceNews.h"
#import "UserDefaultsUtils.h"
#import "PushNotificationService.h"
#import "ShareService.h"
#import "FMDBHelpers.h"
#import "UIAlertView+Blocks.h"

#import "HomeTabBarController.h"
#import "LeftMenuViewController.h"

#import "NewsDetailViewController.h"
#import "SpecialNewsListViewController.h"

#import "ServiceUser.h"
#import "ServiceNews.h"
#import "AccountManager.h"

#import "RCDLive.h"
#import "RCDLiveKitCommonDefine.h"
#import "RCDLiveGiftMessage.h"
#import <RongIMLib/RongIMLib.h>
#import "AppOpenView.h"
#import "UIImageView+WebCache.h"
#import "NewsWebViewController.h"
#import "ReportDetailViewController.h"
#import "PocketNewspapersViewController.h"
#import <MobLink/MobLink.h>
#import <MobLink/MLSDKScene.h>
#import "ShareView.h"
#import <SDWebImage.h>
#import "ServiceUserNew.h"

@interface AppDelegate ()<IMLSDKRestoreDelegate>

@property (nonatomic, strong) AppWizardView *appWizardView;
@property (nonatomic, strong) AppADView *appADView;
@property (nonatomic, strong) AppOpenView *appOpenView;
@end

@implementation AppDelegate

@synthesize myOpen;

+ (instancetype)sharedAppDelegate
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

-(void)testHttp
{
    NSURL *url = [NSURL URLWithString:@"http://www.ctdsb.net/index.php?m=app&c=weixin&a=classify"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    }];
    [dataTask resume];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //推送设置
    [PushNotificationService registerPushNotification:launchOptions];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMessage:) name:MobPushDidReceiveMessageNotification object:nil];
    
    [self testHttp];
    
    [MobLink setDelegate:self];
        
    myOpen = [NSString stringWithFormat:@"0"];
    
    if ([AccountManager sharedAccountManager].f_isLogined) {
        [ServiceUser doGetUserInfo:[AccountManager sharedAccountManager].f_uid
                           success:^(id responseObject, NSString *message)
         {
             
             
         }
                           failure:^(NSString *message)
         {
             
             
         }];
    }
    
    [ServiceNews doFetchAD:^(id responseObject, NSString *message) {
        
    }failure:^(NSString *message) { }];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //self.window.rootViewController = [HomeTabBarController new];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[HomeTabBarController new]];
    self.window.rootViewController = nav;
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    [application setStatusBarHidden:YES];
    
    if(![UserDefaultsUtils valueWithKey:@"firstLaunch"])
    {
        [AccountManager sharedAccountManager].f_authCode = [self getAuthCode];//第一次装机 保存一个码
        
        self.appWizardView = [[AppWizardView alloc]initWithFrame:self.window.bounds];
        [self.window.rootViewController.view addSubview:self.appWizardView];
        
        @try {
            [ServiceNews doFetchAppOpenImage:url_appopen_image success:^(id responseObject, NSString *message) {
                M_AppOpenImage *imageInfo = (M_AppOpenImage *)responseObject;
                
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                NSString *idstr = [defaults objectForKey:@"kctappopenimg_id"];
                NSString *secondsstr = [defaults objectForKey:@"kctappopenimg_seconds"];
                NSString *url = [defaults objectForKey:@"kctappopenimg_url"];
                UIImage *chkImg = [[SDImageCache  sharedImageCache] imageFromDiskCacheForKey:@"kctappopenimg_real"];
                if(chkImg==nil || idstr==nil || ![idstr isEqualToString:imageInfo.f_id]) {
                    url = imageInfo.f_wakeupUrl;
                    secondsstr = [NSString stringWithFormat:@"%ld",imageInfo.f_seconds];

                    UIImage *adImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageInfo.f_wakeupThumb ]]];
                    if(adImage) {
                        [[SDImageCache sharedImageCache] storeImage:adImage forKey:@"kctappopenimg_thumb" toDisk:YES completion:nil];
                    }
                    
                    UIImage *adRealImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageInfo.f_wakeUpPic ]]];
                    if(adRealImage) {
                        [[SDImageCache sharedImageCache] storeImage:adRealImage forKey:@"kctappopenimg_real" toDisk:YES completion:nil];
                    }
                    [defaults setObject:imageInfo.f_id forKey:@"kctappopenimg_id"];
                    [defaults setObject:secondsstr  forKey:@"kctappopenimg_seconds"];
                    [defaults setObject:url  forKey:@"kctappopenimg_url"];
                    [defaults synchronize];
                }
                
                [defaults setObject:imageInfo.f_refreshTags forKey:@"refreshTags"];
                [defaults synchronize];
                
            } failure:^(NSString *message) {
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                [defaults removeObjectForKey:@"kctappopenimg_id"];
            }];
        } @catch (NSException *exception) {
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            [defaults removeObjectForKey:@"kctappopenimg_id"];
            [application setStatusBarHidden:NO];
        }
        
        
    }else {
//        self.appADView=[[AppADView alloc]initWithFrame:self.window.bounds];
//        [_sideMenuViewController.view addSubview:self.appADView];
        
        
        @try {
            [ServiceNews doFetchAppOpenImage:url_appopen_image success:^(id responseObject, NSString *message) {
                M_AppOpenImage *imageInfo = (M_AppOpenImage *)responseObject;
                
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                NSString *idstr = [defaults objectForKey:@"kctappopenimg_id"];
                NSString *secondsstr = [defaults objectForKey:@"kctappopenimg_seconds"];
                NSString *url = [defaults objectForKey:@"kctappopenimg_url"];
                UIImage *chkImg = [[SDImageCache  sharedImageCache] imageFromDiskCacheForKey:@"kctappopenimg_real"];
                if(chkImg==nil || idstr==nil || ![idstr isEqualToString:imageInfo.f_id]) {
                    url = imageInfo.f_wakeupUrl;
                    secondsstr = [NSString stringWithFormat:@"%ld",imageInfo.f_seconds];

                    UIImage *adImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageInfo.f_wakeupThumb ]]];
                    if(adImage) {
                        [[SDImageCache sharedImageCache] storeImage:adImage forKey:@"kctappopenimg_thumb" toDisk:YES completion:nil];
                    }
                
                    UIImage *adRealImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageInfo.f_wakeUpPic ]]];
                    if(adRealImage) {
                        [[SDImageCache sharedImageCache] storeImage:adRealImage forKey:@"kctappopenimg_real"  toDisk:YES completion:nil];
                    }
                    [defaults setObject:imageInfo.f_id forKey:@"kctappopenimg_id"];
                    [defaults setObject:secondsstr  forKey:@"kctappopenimg_seconds"];
                    [defaults setObject:url  forKey:@"kctappopenimg_url"];
                    [defaults synchronize];
                }
                
                [defaults setObject:imageInfo.f_refreshTags forKey:@"refreshTags"];
                [defaults synchronize];

                NSInteger oldTime = [defaults integerForKey:@"kctappopenimg_time"];
                NSInteger nowTime = [self longLongFromDate:nil];
                if(oldTime==0 || (nowTime-oldTime)> 300) {
                    [defaults setInteger:nowTime forKey:@"kctappopenimg_time"];
                    [defaults synchronize];
                
                    self.appOpenView=[[AppOpenView alloc]initWithFrame:self.window.bounds];
                    self.appOpenView.waitSec = [secondsstr integerValue];
                    self.appOpenView.url = url;
                
                    if(self.appOpenView.url) {
                        self.appOpenView.adImageview.userInteractionEnabled=YES;
                        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap)];
                        [self.appOpenView.adImageview addGestureRecognizer:singleTap];
                    }
                    [self.window.rootViewController.view addSubview:self.appOpenView];
                }else {
                    [application setStatusBarHidden:NO];
                }
            } failure:^(NSString *message) {
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                [defaults removeObjectForKey:@"kctappopenimg_id"];
            }];
        } @catch (NSException *exception) {
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            [defaults removeObjectForKey:@"kctappopenimg_id"];
            [application setStatusBarHidden:YES];
        }

    }

    [self.window makeKeyAndVisible];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.maskWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.maskWindow.windowLevel = UIWindowLevelStatusBar + 1;
        self.maskWindow.userInteractionEnabled = NO;
        self.maskWindow.backgroundColor = [UIColor blackColor];
        if ([[NSUserDefaults standardUserDefaults] boolForKey:kNightMode]) {
            self.maskWindow.alpha = 0.7;
        } else {
            self.maskWindow.alpha = 0;
        }
        [self.maskWindow makeKeyAndVisible];
        [self.window makeKeyWindow];
    });
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        self.appADView=[[AppADView alloc]initWithFrame:self.window.bounds];
//        [_sideMenuViewController.view addSubview:self.appADView];
//    });

    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    // app名称
//    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    // app版本
    self.app_Version =  [infoDictionary objectForKey:@"CFBundleShortVersionString"];

    [self sharesdkInit];
    
    [[RCDLive sharedRCDLive] initRongCloud:RONGCLOUD_IM_APPKEY];
    //注册自定义消息
    [[RCDLive sharedRCDLive] registerRongCloudMessageType:[RCDLiveGiftMessage class]];

    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"RoleList" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    _userList = [[NSMutableArray alloc]init];
    
    //设置程序webview的 UserAgent
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newAgent = [oldAgent stringByAppendingString:@";KCT/6"];//add my info to the new agent
    NSDictionary *dictionary = @{@"UserAgent" : newAgent};
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    
    //创建数据库
    [[FMDBHelpers sharedInstance] createZanTable];

    // 获取本机ip
    [ServiceNews doFetchMyIp:nil failure:nil];

    BOOL aaa = [MobPush isPushStopped];
    NSLog(@"---------- %d",aaa);
    return YES;
    
}

// 收到通知回调
- (void)didReceiveMessage:(NSNotification *)notification
{
    MPushMessage *message = notification.object;

    switch (message.messageType)
    {
        case MPushMessageTypeCustom:
        {// 自定义消息

       }
            break;
        case MPushMessageTypeAPNs:
        {// APNs 回调

            if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
            { // 前台

           }
            else
            { // 后台

           }
        }
            break;
        case MPushMessageTypeLocal:
        { // 本地通知回调
            NSString *body = message.notification.body;
            NSString *title = message.notification.title;
            NSString *subtitle = message.notification.subTitle;
            NSInteger badge = message.notification.badge;
            NSString *sound = message.notification.sound;

            NSLog(@"收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%ld，\nsound：%@，\n}",body, title, subtitle, badge, sound);
        }
            break;
        case MPushMessageTypeClicked:
        {
            NSLog(@"click the message!!!!!!!!!!!!");
        }
            break;
        default:
            break;
    }
}

-(long long)longLongFromDate:(NSDate*) fromdate{
    if(fromdate==nil) {
        fromdate = [NSDate date];
    }
    //return [fromdate timeIntervalSince1970] * 1000;//毫秒
    return [fromdate timeIntervalSince1970] ;
}


- (void)handleSingleTap{
    if(self.appOpenView) {
        
        // 点击封面加积分
        [ServiceUserNew doAddScore:AddScoreType_clickrmt
                           success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {}
                           failure:^(NSString * _Nonnull message) {}];
        
        [self.appOpenView removeFromSuperview];
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        [self.appOpenView stopTimer];
    }
    
    //外链新闻
    if (self.appOpenView.url && [self.appOpenView.url length] > 0) {
        NewsWebViewController *controller = [NewsWebViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        controller.urlString = self.appOpenView.url;
        [[self visibleViewController] showViewController:controller sender:nil];
    }

}

- (RCUserInfo *)parseUserInfoFormDic:(NSDictionary *)dic{
    RCUserInfo *user = [[RCUserInfo alloc]init];
    user.userId = [dic objectForKey: @"id" ];
    user.name = [dic objectForKey: @"name" ];
    user.portraitUri = [dic objectForKey: @"icon" ];
    return user;
}

- (NSString *)getAuthCode
{
    long long timestamp = (long long)[[NSDate date] timeIntervalSince1970];
    NSString *random = [NSString stringWithFormat:@"%d%d%d",arc4random() % 10,arc4random() % 10,arc4random() % 10];
    NSString *code = [NSString stringWithFormat:@"20%lld%@001",timestamp,random];
    NSData *codeData = [code dataUsingEncoding:NSUTF8StringEncoding];
    NSString *codeBase64 = [codeData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return codeBase64;
}

- (void)sharesdkInit
{
    //分享相关的配置
    [ShareService registerUMeng];
    [ShareService registerWechat];
    [ShareService registerSina];
    [ShareService registerQQ];
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
    if (![[UMSocialManager defaultManager] handleUniversalLink:userActivity options:nil]) {
        // 其他SDK的回调
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

/**
 这里处理新浪微博SSO授权进入新浪微博客户端后进入后台，再返回原来应用
 */
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kApplicationWillEnterForeground object:nil userInfo:nil];
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString *idstr = [defaults objectForKey:@"kctappopenimg_id"];
    NSString *url = [defaults objectForKey:@"kctappopenimg_url"];
    UIImage *chkImg = [[SDImageCache  sharedImageCache] imageFromDiskCacheForKey:@"kctappopenimg_real"];
    if(idstr==nil || chkImg==nil) {
    @try {
        [ServiceNews doFetchAppOpenImage:url_appopen_image success:^(id responseObject, NSString *message) {
            M_AppOpenImage *imageInfo = (M_AppOpenImage *)responseObject;
            
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            NSString *idstr = [defaults objectForKey:@"kctappopenimg_id"];
            NSString *secondsstr = [defaults objectForKey:@"kctappopenimg_seconds"];
            NSString *url = [defaults objectForKey:@"kctappopenimg_url"];
            
            url = imageInfo.f_wakeupUrl;
            secondsstr = [NSString stringWithFormat:@"%ld",imageInfo.f_seconds];
                
            UIImage *adImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageInfo.f_wakeupThumb ]]];
            if(adImage) {
                [[SDImageCache sharedImageCache] storeImage:adImage forKey:@"kctappopenimg_thumb" toDisk:YES completion:nil];
            }
                
            UIImage *adRealImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageInfo.f_wakeUpPic ]]];
            if(adRealImage) {
                [[SDImageCache sharedImageCache] storeImage:adRealImage forKey:@"kctappopenimg_real" toDisk:YES completion:nil];
            }
            [defaults setObject:imageInfo.f_id forKey:@"kctappopenimg_id"];
            [defaults setObject:secondsstr  forKey:@"kctappopenimg_seconds"];
            [defaults setObject:url  forKey:@"kctappopenimg_url"];
            [defaults setObject:imageInfo.f_refreshTags forKey:@"refreshTags"];
            [defaults synchronize];
        } failure:^(NSString *message) {
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                [defaults removeObjectForKey:@"kctappopenimg_id"];
            }];
        } @catch (NSException *exception) {
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            [defaults removeObjectForKey:@"kctappopenimg_id"];
            [application setStatusBarHidden:YES];
        }
    }

     idstr = [defaults objectForKey:@"kctappopenimg_id"];

    [application setStatusBarHidden:YES];
    if(idstr ||(self.appOpenView && self.appOpenView.url)) {
        NSInteger oldTime = [defaults integerForKey:@"kctappopenimg_time"];
        NSInteger nowTime = [self longLongFromDate:nil];
        if(oldTime==0 || (nowTime-oldTime)> 300) {
            [defaults setInteger:nowTime forKey:@"kctappopenimg_time"];
            [defaults synchronize];
            NSString *secondsstr = [defaults objectForKey:@"kctappopenimg_seconds"];
            NSString *url = [defaults objectForKey:@"kctappopenimg_url"];
            if(secondsstr) {
                NSInteger seconds = [secondsstr integerValue];
                if(seconds>0) {
                    self.appOpenView=[[AppOpenView alloc]initWithFrame:self.window.bounds];
                    [self.window.rootViewController.view addSubview:self.appOpenView];
                    self.appOpenView.url = url;
                    if(self.appOpenView.url) {
                        self.appOpenView.adImageview.userInteractionEnabled=YES;
                        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap)];
                        [self.appOpenView.adImageview addGestureRecognizer:singleTap];
                    }
                }
            }
        }else {
            [application setStatusBarHidden:NO];
        }
    }else {
        [application setStatusBarHidden:NO];
    }
    [application setApplicationIconBadgeNumber:0];
}
                 
- (void)touchImageView {
        //外链新闻
        NewsWebViewController *controller = [NewsWebViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        controller.urlString = self.appOpenView.url;
                     //    NewsDetailViewController *controller = [NewsDetailViewController new];
                     //    controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,id_];
                     
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
        [self.window.rootViewController presentViewController:navController animated:YES completion:^{
                         
        }];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    __weak typeof(self) weak_self = self;
    
    [application setApplicationIconBadgeNumber:0];
    
    NSString *aid = [userInfo objectForKey:@"aid"];
    NSString *msgType = [userInfo objectForKey:@"type"];
    
    if (aid && aid.length) {
        if (application.applicationState == UIApplicationStateActive)//处于前台
        {
            if (msgType != nil && [msgType isEqualToString:@"zt"]) {
                //专题
                NSString *message = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
                
                [UIAlertView showWithTitle:@"专题新闻推送" message:message cancelButtonTitle:@"忽略" otherButtonTitles:@[@"点击查看"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1)
                    {
                        [weak_self openRemoteNotificationWithIDToSpecialNews:aid];
                    }
                }];
            } else {
                //普通新闻
                NSString *message = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
                
                [UIAlertView showWithTitle:@"要闻推送" message:message cancelButtonTitle:@"忽略" otherButtonTitles:@[@"点击查看"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1)
                    {
                        [weak_self openRemoteNotificationWithID:aid];
                    }
                }];
            }
        }
        else if (application.applicationState == UIApplicationStateInactive)
        {
            if (msgType != nil && [msgType isEqualToString:@"zt"]) {
                //专题
                [self openRemoteNotificationWithIDToSpecialNews:aid];
            } else {
                //普通新闻
                [self openRemoteNotificationWithID:aid];
            }
        }
    }
    
    // [APService handleRemoteNotification:userInfo];// App 收到推送的通知

    completionHandler(UIBackgroundFetchResultNoData);
}

- (void)openRemoteNotificationWithID:(NSString *)id_
{
    NewsDetailViewController *controller = [NewsDetailViewController new];
    controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,id_];
    
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
    [self.window.rootViewController presentViewController:navController animated:YES completion:^{
        
    }];
}

- (void)openRemoteNotificationWithIDToSpecialNews:(NSString *)id_
{
    SpecialNewsListViewController *specialNewsListViewController = [[SpecialNewsListViewController alloc] initWithNibName:@"SpecialNewsListViewController" bundle:[NSBundle mainBundle]];
    specialNewsListViewController.subURL              = [NSString stringWithFormat:@"%@&specialid=%@",URL_SUB_GET_SPECIAL_NEWS,id_];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:specialNewsListViewController];
    [self.window.rootViewController presentViewController:navController animated:YES completion:^{
        
    }];
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // [APService registerDeviceToken:deviceToken];
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [application setApplicationIconBadgeNumber:0];
    
    // [APService handleRemoteNotification:userInfo];// App 收到推送的通知
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[NSNotificationCenter defaultCenter] postNotificationName:kApplicationDidEnterBackground object:nil userInfo:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [ServiceNews doFetchMyIp:nil failure:nil];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
    [AccountManager sharedAccountManager].f_ip = @"";
    
    NSLog(@"terminate exit");
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString *idstr = [defaults objectForKey:@"kctappopenimg_id"];
    if(idstr) {
        [defaults removeObjectForKey:@"kctappopenimg_time"];
        [defaults synchronize];
    }
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    
}

-(CGSize)sizeWithFont:(int)f lable:(UILabel*)label{
    
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:f]};
    CGSize size = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    return size;
}

- (UIImage*)createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}




//将键盘推出时候，view重新回到原来位置
//
-(void)viewKeyboardDisappearChangeRect:(UIView*)view{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    //把view设置回默认的Rect
    CGRect rect = CGRectMake(0.0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    view.frame = rect;
    
    [UIView commitAnimations];
}

//
//view要往上推
//@offset:要推的高度偏移
//
-(void)viewKeyboardAppearChangeRect:(int)offset View:(UIView*)view{
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:0.30f];
    
    if (offset > 0) {
        
        view.frame = CGRectMake(0, -offset, SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    [UIView commitAnimations];
}

#pragma mark ----------------- 时间戳 --------------------
//yyyy-MM-dd HH:mm
-(NSString*)confromTimesp:(NSString*)update :(NSString*)format
{
    double timeInterval = [update doubleValue];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    
    //时间戳转时间的方法
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    
    return confromTimespStr;
}


-(void)alert:(NSString*)message{
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"用户提示" message:message delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark Show Methods Sample
- (void)showWithStatus:(UIView*)view Label:(NSString*)text{
    
    //方式1.直接在View上show
    HUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    HUD.delegate = self;
    
    //常用的设置
    //小矩形的背景色
    HUD.color = [UIColor blackColor];//这儿表示无背景
    //显示的文字
    //    HUD.labelText = @"Test";
    //细节文字
    HUD.labelText = text;
    //是否有庶罩
    //    HUD.dimBackground = YES;
    
    
}

#pragma mark Dismiss Methods Sample
- (void)dismiss {
    
    [self hudWasHidden:HUD];
    
}

#pragma mark -----------HUD的代理方法,关闭HUD时执行

-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [hud removeFromSuperview];
    hud = nil;
}

-(void)settitle:(UIView*)view title:(NSString*)title{
    UILabel * titlelabel = [[UILabel alloc]initWithFrame:NSRect(0, 20, SCREEN_WIDTH, 44)];
    [titlelabel setTextColor:Maintextcolors];
    [titlelabel setText:title];
    titlelabel.font = Font(navredsize);
    titlelabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:titlelabel];
    
}

- (void)closeMy{
    myOpen = [NSString stringWithFormat:@"0"];
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.allowRotation) {
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (void)showOpenView {
    //显示启动页面
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    //NSInteger oldTime = [defaults integerForKey:@"kctappopenimg_time"];
    //NSInteger nowTime = [self longLongFromDate:nil];
    NSString *secondsstr = [defaults objectForKey:@"kctappopenimg_seconds"];
    NSString *url = [defaults objectForKey:@"kctappopenimg_url"];
    if(secondsstr) {
        NSInteger seconds = [secondsstr integerValue];
        if(seconds>0) {
            [[UIApplication sharedApplication] setStatusBarHidden:YES];
            self.appOpenView=[[AppOpenView alloc]initWithFrame:self.window.bounds];
            [self.window.rootViewController.view addSubview:self.appOpenView];
            self.appOpenView.url = url;
            if(self.appOpenView.url) {
                self.appOpenView.adImageview.userInteractionEnabled=YES;
                UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap)];
                [self.appOpenView.adImageview addGestureRecognizer:singleTap];
            }
        }
    }
}

//MARK: - IMLSDKRestoreDelegate
- (void)IMLSDKStartCheckScene {
    NSLog(@"Start Check Scene");
}

- (void)IMLSDKEndCheckScene {
    NSLog(@"End Check Scene");
}

-(void) IMLSDKWillRestoreScene:(MLSDKScene *)scene Restore:(void (^)(BOOL, RestoreStyle))restoreHandler
{
    NSLog(@"Will Restore Scene - Path:%@",scene.path);
    
    NSString *type = scene.params[@"type"];
    
    //跳转新闻详情
    if ([type isEqualToString:@"newsDetail"]) {
        NewsDetailViewController *controller = [NewsDetailViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        controller.urlString = [scene.params objectForKey:@"urlString"];
        [self.window.rootViewController showViewController:controller sender:nil];
        return;
    }
    
    //爆料详情
    if ([type isEqualToString:@"baoLiaoDetail"]) {
        UIStoryboard *PersonalStoryboard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
        ReportDetailViewController *controller = [PersonalStoryboard instantiateViewControllerWithIdentifier:@"ReportDetailViewController"];
        controller.hidesBottomBarWhenPushed = YES;
        controller.baoLiaoId = [scene.params objectForKey:@"baoLiaoId"];
        [self.window.rootViewController showViewController:controller sender:nil];
        return;
    }

    //专题列表
    if ([type isEqualToString:@"zhuanti"]) {
        SpecialNewsListViewController *controller = [SpecialNewsListViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        controller.sharethumb = [scene.params objectForKey:@"sharethumb"];
        controller.sharetitle = [scene.params objectForKey:@"sharetitle"];
        controller.subURL = [scene.params objectForKey:@"subURL"];
        [self.window.rootViewController showViewController:controller sender:nil];
        return;
    }
    
    //掌报
    
    if ([type isEqualToString:@"zhangbao"]) {
        PocketNewspapersViewController *controller = [PocketNewspapersViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        [self.window.rootViewController showViewController:controller sender:nil];
        return;
    }

}

- (void)IMLSDKCompleteRestore:(MLSDKScene *)scene
{
    NSLog(@"Complete Restore -Path:%@",scene.path);
}

- (void)IMLSDKNotFoundScene:(MLSDKScene *)scene
{
    NSLog(@"Not Found Scene - Path :%@",scene.path);
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"没有找到路径"
                                                        message:[NSString stringWithFormat:@"Path:%@",scene.path]
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    
}

- (UIViewController *)visibleViewController
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self visibleViewController:rootViewController];
}

- (UIViewController *)visibleViewController:(UIViewController *)rootViewController
{
    if ([rootViewController isKindOfClass:[UINavigationController class]])
    {
        UINavigationController *navigationController = (UINavigationController *)rootViewController;
        UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
        
        return [self visibleViewController:lastViewController];
    }
    if ([rootViewController isKindOfClass:[UITabBarController class]])
    {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        UIViewController *selectedViewController = tabBarController.selectedViewController;
        
        return [self visibleViewController:selectedViewController];
    }
    
    if (rootViewController.presentedViewController != nil)
    {
        UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
        return [self visibleViewController:presentedViewController];
    }
    
    if (rootViewController.childViewControllers != nil && rootViewController.childViewControllers.count > 0) {
        
        UIViewController *tabChild = nil;
        for (UIViewController *child in rootViewController.childViewControllers) {
            if ([child isKindOfClass:[UITabBarController class]]) {
                tabChild = child;
            }
        }
        
        if (tabChild) {
            return [self visibleViewController:tabChild];
        }
    }
    
    return rootViewController;
}

@end
